﻿namespace dotnet_notes.Extensions
{
    /// <summary>
    /// 字符串扩展类
    /// </summary>
    public static class StringExtension
    {
        /// <summary>
        /// 获取可空字符串的值(为 null 则返回空字符串)
        /// </summary>
        public static string GetValue(this string? str)
        {
            return str ?? "";
        }

        /// <summary>
        /// 判断字符串是否不为 null、空字符串和空格
        /// </summary>
        public static bool HasValue(this string? str)
        {
            return !string.IsNullOrWhiteSpace(str);
        }

        /// <summary>
        /// 字符串转 int
        /// </summary>
        /// <param name="str"></param>
        /// <param name="defaultValue">转换失败的默认返回值(默认 0)</param>
        /// <returns></returns>
        public static int ToInt(this string? str, int defaultValue = 0)
        {
            if (int.TryParse(str, out int number))
            {
                return number;
            }

            return defaultValue;
        }

        /// <summary>
        /// 字符串转 bool
        /// </summary>
        public static bool ToBool(this string? str)
        {
            if (bool.TryParse(str, out bool output))
            {
                return output;
            }

            throw new InvalidCastException($"参数 {nameof(str)} 不是一个有效的 bool 值");
        }
    }
}
